package com.yunquan.ohana.ui.history.list

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.ui.BaseFragment
import com.yunquan.ohana.databinding.FragmentHistoryListBinding
import com.yunquan.ohana.dialog.TipDialog
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.entity.FileGroupEntity
import com.yunquan.ohana.entity.FramesEntity
import com.yunquan.ohana.entity.LocalFileEntity
import com.yunquan.ohana.entity.LocalFrameEntity
import com.yunquan.ohana.ui.history.list.adapter.HistoryListAdapter
import com.yunquan.ohana.ui.selectFrames.SelectFramesActivity
import java.util.UUID

class HistoryListFragment(private val type: String) : BaseFragment<FragmentHistoryListBinding, HistoryListViewModel>() {

    private var mAdapter: HistoryListAdapter? = null

    override fun initContentView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): Int {
        return R.layout.fragment_history_list
    }

    override fun initVariableId(): Int {
        return BR.historyListViewModel
    }

    override fun initData(savedInstanceState: Bundle?) {
        mAdapter = HistoryListAdapter()
        binding!!.adapter = mAdapter
        viewModel!!.showType.set(type)
        if(type == "Completed") {
            binding!!.layoutRefresh.post {
                binding!!.layoutRefresh.isRefreshing = true
            }
        }
        viewModel!!.onRefresh()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        binding!!.layoutRefresh.setOnRefreshListener {
            binding!!.layoutRefresh.isRefreshing = true
            viewModel!!.onRefresh()
        }
        binding!!.rvHistoryList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (viewModel!!.items.size >= 30) {
                    val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                    val lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition()
                    if (lastVisibleItem == (mAdapter?.itemCount ?: 0) - 1) {
                        viewModel!!.onLoadMove()
                    }
                }
            }
        })
        viewModel!!.ui.observe(viewLifecycleOwner) { type ->
            when (type) {
                0 -> {
                    //撤回
                    val dialog = TipDialog(requireContext())
                    if (viewModel!!.mCurrentItem?.data?.photos?.get(0)?.type == 1) {
                        dialog.setTitle("Withdraw Current Images?")
                    } else {
                        dialog.setTitle("Withdraw Current Video?")
                    }
                    dialog.setOnDialogClickListener(object : TipDialog.OnDialogClickListener() {
                        override fun onLeftClick() {
                            super.onLeftClick()
                            viewModel!!.mCurrentItem = null
                        }

                        override fun onRightClick() {
                            super.onRightClick()
                            viewModel!!.deleteAlbum(true)
                        }
                    })
                    dialog.show()
                }

                1 -> {
                    //删除
                    val dialog = TipDialog(requireContext())
                    dialog.setTitle(getString(R.string.title_delete_record))
                    dialog.setMessage(getString(R.string.tip_delete_record))
                    dialog.setOnDialogClickListener(object : TipDialog.OnDialogClickListener() {
                        override fun onLeftClick() {
                            super.onLeftClick()
                            viewModel!!.mCurrentItem = null
                        }

                        override fun onRightClick() {
                            super.onRightClick()
                            viewModel!!.deleteAlbum(false)
                        }
                    })
                    dialog.show()
                }

                2 -> {
                    // 重发
                    val intent = Intent(requireContext(), SelectFramesActivity::class.java)
                    mFramesResult.launch(intent)
                }

                3 -> {
                    binding!!.layoutRefresh.isRefreshing = false
                }
                4->{
                    binding!!.layoutRefresh.isRefreshing = true
                }
                5->{ // 滚回头部
                    binding!!.rvHistoryList.scrollToPosition(0)
                }
            }
        }
    }

    // 这里处理返回结果
    private val mFramesResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == SelectFramesActivity.RESULT_CODE) {
            // 获取相框返回
            val bundle = result.data?.extras
            val framesJson = bundle?.getString("frames")
            val listType = object : TypeToken<List<FramesEntity>>() {}.type
            val frames: List<FramesEntity> = Gson().fromJson(framesJson, listType)
            val oldGroupId = viewModel!!.mCurrentItem!!.data!!.groupId
            val type = viewModel!!.mCurrentItem!!.data!!.photos[0].type
            val groupId = UUID.randomUUID().toString()
            val localFrames = frames.map { e ->
                LocalFrameEntity(
                    deviceId = e.id,
                    name = e.name,
                    location = e.roomLocation,
                    online = if (e.online == true) 1 else 0,
                    receipt = false
                )
            }
            val localPhotos = viewModel!!.mCurrentItem!!.data!!.photos.map { e ->
                LocalFileEntity(
                    id = null,
                    serviceId = e.serviceId,
                    groupId = groupId,
                    serviceGroupId = null,
                    content = e.content,
                    fileName = e.fileName,
                    fileUrl = e.fileUrl,
                    localFileId = e.localFileId,
                    localFilePath = e.localFilePath,
                    localCropId = e.localCropId,
                    localCropPath = e.localCropPath,
                    videoImgUrl = e.videoImgUrl,
                    thumbnail = e.thumbnail,
                    duration = e.duration,
                    height = e.height,
                    width = e.width,
                    status = 0,
                    type = type,
                    createTime = e.createTime,
                )
            }
            val bean = FileGroupEntity(
                groupId = groupId,
                serviceGroupId = null,
                frames = localFrames,
                photos = localPhotos,
            )
            RxBus.getDefault().post(EventEntity(EventType.RESEND_DELETE, oldGroupId))
            RxBus.getDefault().post(EventEntity(EventType.RESEND, bean))
        }
    }
}